package com.ruoyi.system.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

@ServerEndpoint("/ws/{carId}")
@Component
public class WebSocketServer {

    private static HashMap<String,WebSocketServer> webSocketServerHashMap=new HashMap<>();

    private Session session;  //连接会话

    private  String carId;

    @OnOpen
    public void onOpen(Session session,@PathParam("carId") String carId){
        this.session=session;
        this.carId=carId;
        webSocketServerHashMap.put(carId,this);
    }

    @OnClose
    public  void  onClose(){
        webSocketServerHashMap.remove(carId);
    }

    @OnMessage
    public  void onMessage(String message,Session session){
        System.out.println(carId+"收到的消息"+message);
        //做处理

    }

    //主动去给客户发送消息
    public  void  sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendInfo(String message,String carId) throws IOException {
        System.out.println("发送给"+carId+"消息"+message);
        webSocketServerHashMap.get(carId).sendMessage(message);
    }


    public static  HashMap<String,WebSocketServer> getWebSocketServeHashMap(){
        return webSocketServerHashMap;
    }

    public static void  setWebSocketServeHashMap(HashMap<String,WebSocketServer> socketServeHashMap){
        WebSocketServer.webSocketServerHashMap=socketServeHashMap;
    }


}
